package org.example.dao;

import org.example.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 接口访问统计数据访问类
 */
public class UriViewDao {
    
    /**
     * 增加接口访问次数
     */
    public void incrementViewCount(String uri) {
        String sql = "INSERT INTO uri_views (uri, view_num) VALUES (?, 1) " +
                    "ON DUPLICATE KEY UPDATE view_num = view_num + 1";
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, uri);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeResources(pstmt, conn);
        }
    }
    
    /**
     * 获取所有接口访问统计
     */
    public List<UriView> getAllUriViews() {
        String sql = "SELECT uri, view_num FROM uri_views ORDER BY uri";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<UriView> uriViews = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                UriView uriView = new UriView();
                uriView.setUri(rs.getString("uri"));
                uriView.setViewNum(rs.getInt("view_num"));
                uriViews.add(uriView);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeResources(rs, pstmt, conn);
        }
        
        return uriViews;
    }
    
    /**
     * 接口访问统计实体类
     */
    public static class UriView {
        private String uri;
        private int viewNum;
        
        // Getters and Setters
        public String getUri() {
            return uri;
        }
        
        public void setUri(String uri) {
            this.uri = uri;
        }
        
        public int getViewNum() {
            return viewNum;
        }
        
        public void setViewNum(int viewNum) {
            this.viewNum = viewNum;
        }
    }
}
